<?php
/**
 * controller基础类，别的controller都继承此类。
 *
 * controller里的每个函数都是一个action动作。
 * @todo 此类中要包含哪些功能，还没有界定清楚，可能变成垃圾箱。
 */
abstract class BasicController
{
    protected static $input;
    protected static $content_type;
    protected static $version;
    
    protected function __construct()
    {
        $input = array();
        switch($_SERVER['REQUEST_METHOD'])
        {
            case 'GET':
                $input = $_GET;
                break;
            case 'POST':
                $input = $_POST;
                break;
            case 'PUT':
            case 'DELETE':
                parse_str(file_get_contents('php://input'), $input); 
                break;
        }
        $tmp = explode(';', $_SERVER['HTTP_ACCEPT']); //比如application/json; version=0.2
        //考虑复杂情况，比如text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        $content_type = '';
        foreach($tmp as $one)
        {
            $one = strtolower(trim($one));
            if(empty(self::$content_type) && stripos($one, 'application/json')!==false)
            {
                self::$content_type = 'application/json';
                continue;
            }
            if(empty(self::$content_type) && stripos($one, 'application/xml')!==false)
            {
                self::$content_type = 'application/xml';
                continue;
            }
            if(stripos($one, 'version')===0)
            {
                self::$version = substr($one, stripos($one, '=')+1);
                continue;
            }
        }
    }
    
    /**
     * http输出。
     * @param array $data 要输出的数据
     * @param string $content_type 输出格式json，xml，plain
     * @todo 既然是static，应该放lib里？
     */
    public static function output($r)
    {
        //参考http://cn2.php.net/manual/en/function.header.php
        header('HTTP/1.1 ' . $r['result']['status']['code'] . ' ' . $r['result']['status']['msg']); //module
        header('Status: ' . $r['result']['status']['code'] . ' ' . $r['result']['status']['msg']); //cgi
        switch (self::$content_type)
        {
            case 'application/json' :
                header('Content-Type: application/json; charset=UTF-8'); //google.com用的是UTF-8。没找到标准规定大小写。todo
                if((!isset($r['result']['data']))||(!is_array($r['result']['data'])))
                {
                    $r['result']['data'] = (object)array(); //一直输出json对象
                }
                echo json_encode($r);
                break;
            case 'application/xml' :
                header('Content-Type: application/xml; charset=UTF-8');
                //todo array to xml
                break;
            case 'image/jpeg' :
            case 'image/png' :
                header('Content-Type: ' . self::$content_type);
                echo file_get_contents($r['result']['data']['file']);
                break;
            default :
                header('Content-Type: ' . $self::content_type);
        }
        return true;
    }
}
?>
